let popup = null;
let translateIcon = null;

// 百度翻译 API 配置
const BAIDU_APPID = '20220121001061842';
const BAIDU_KEY = 'xqxdXhX7Dnqa8BE8q62Q';

// 创建翻译图标
function createTranslateIcon() {
  // 检查是否已存在图标
  const existingIcon = document.getElementById('translate-icon');
  if (existingIcon) {
    return existingIcon;
  }

  const icon = document.createElement('div');
  icon.id = 'translate-icon';
  icon.className = 'translate-icon';
  icon.innerHTML = 'T';
  icon.style.display = 'none';
  icon.style.position = 'fixed';
  icon.style.zIndex = '2147483647';
  
  // 将图标添加到 body 的最后
  document.documentElement.appendChild(icon);
  return icon;
}

// 创建翻译弹窗
function createPopup() {
  // 检查是否已存在弹窗
  const existingPopup = document.getElementById('translation-popup');
  if (existingPopup) {
    return existingPopup;
  }

  const div = document.createElement('div');
  div.id = 'translation-popup';
  div.className = 'translation-popup';
  
  // 将弹窗添加到 body 的最后
  document.documentElement.appendChild(div);
  return div;
}

// 显示翻译图标
function showTranslateIcon(x, y) {
  if (!translateIcon) {
    translateIcon = createTranslateIcon();
  }

  const viewportWidth = window.innerWidth;
  const iconWidth = 24;
  
  let finalX = Math.min(x, viewportWidth - iconWidth - 5);
  let finalY = Math.max(0, y);
  
  translateIcon.style.left = `${finalX}px`;
  translateIcon.style.top = `${finalY}px`;
  translateIcon.style.display = 'flex';
}

// 显示弹窗
function showPopup(text, x, y) {
  if (!popup) {
    popup = createPopup();
  }

  popup.innerHTML = `
    <div class="word">${text}</div>
    <div class="loading">正在翻译...</div>
  `;
  
  popup.style.display = 'block';
  
  const viewportWidth = window.innerWidth;
  const viewportHeight = window.innerHeight;
  const popupWidth = popup.offsetWidth;
  const popupHeight = popup.offsetHeight;
  
  let finalX = Math.min(Math.max(0, x), viewportWidth - popupWidth);
  let finalY = y + 20;

  if (finalY + popupHeight > viewportHeight) {
    finalY = y - popupHeight - 10;
  }

  popup.style.left = `${finalX}px`;
  popup.style.top = `${finalY}px`;
}

// 处理翻译请求
async function handleTranslation(text, x, y) {
  showPopup(text, x, y);
  hideTranslateIcon();
  
  try {
    const response = await chrome.runtime.sendMessage({
      type: 'translate',
      text: text
    });
    
    if (response.success && popup) {
      popup.innerHTML = `
        <div class="word">${text}</div>
        <div class="meaning">${response.translation}</div>
      `;
    } else if (popup) {
      popup.innerHTML = `
        <div class="word">${text}</div>
        <div class="meaning">翻译失败: ${response.error || '未知错误'}</div>
      `;
    }
  } catch (error) {
    if (popup) {
      popup.innerHTML = `
        <div class="word">${text}</div>
        <div class="meaning">翻译出错: ${error.message}</div>
      `;
    }
  }
}

// 隐藏翻译图标
function hideTranslateIcon() {
  if (translateIcon) {
    translateIcon.style.display = 'none';
  }
}

// 隐藏弹窗
function hidePopup() {
  if (popup) {
    popup.style.display = 'none';
  }
}

// 事件监听器
function setupEventListeners() {
  // 监听选中文本事件
  document.addEventListener('mouseup', function(e) {
    // 忽略来自翻译图标和弹窗的事件
    if (e.target === translateIcon || (popup && popup.contains(e.target))) {
      return;
    }

    setTimeout(() => {
      const selection = window.getSelection();
      const selectedText = selection.toString().trim();
      
      if (!selectedText) {
        hideTranslateIcon();
        return;
      }
      
      // 检查文本��否包含英文（更宽松的匹配规则）
      if (/[a-zA-Z]/.test(selectedText)) {  // 只要包含英文字母就显示图标
        const range = selection.getRangeAt(0);
        const rect = range.getBoundingClientRect();
        
        const iconX = rect.right + 5;
        const iconY = rect.top - 30;
        
        showTranslateIcon(iconX, iconY);
        
        if (translateIcon) {
          translateIcon.dataset.text = selectedText;
          translateIcon.dataset.x = rect.left;
          translateIcon.dataset.y = rect.top;
        }
      } else {
        hideTranslateIcon();
      }
    }, 10);
  });

  // 监听点击事件
  document.addEventListener('click', function(e) {
    if (e.target === translateIcon) {
      const text = translateIcon.dataset.text;
      const x = parseFloat(translateIcon.dataset.x);
      const y = parseFloat(translateIcon.dataset.y);
      handleTranslation(text, x, y);
    } else if (!popup?.contains(e.target) && e.target !== translateIcon) {
      hidePopup();
      hideTranslateIcon();
    }
  });

  // 监听来自background的消息（用于右键菜单翻译）
  chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.type === 'showTranslation') {
      const selection = window.getSelection();
      const selectedText = request.text;
      
      if (selection && selection.rangeCount > 0) {
        const range = selection.getRangeAt(0);
        const rect = range.getBoundingClientRect();
        
        // 使用选中文本的位置来显示翻译
        handleTranslation(selectedText, rect.left, rect.top);
      } else {
        // 如果获取不到选中区域，使用鼠标位置
        handleTranslation(selectedText, window.mouseX || 0, window.mouseY || 0);
      }
    }
  });

  // 记录鼠标位置
  document.addEventListener('mousemove', function(e) {
    window.mouseX = e.pageX;
    window.mouseY = e.pageY;
  });
}

// 初始化
setupEventListeners();
  